﻿
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sproc_GetStaffByPosition_V2]') AND type in (N'P', N'PC'))
    DROP PROCEDURE [dbo].[sproc_GetStaffByPosition_V2];
GO
CREATE PROCEDURE [dbo].[sproc_GetStaffByPosition_V2]
    @PositionID INT,
    @IncludePeers bit = 1,          -- 是否包含同级成员
    @NumLowerLevels int = 128       -- 指定包含几级下属
/*

============================================================
功能:    得到职位的成员或下级成员
参数:
    @PositionID int         :    职位
    @IncludePeers bit       :    是否包含同级成员
    @NumLowerLevels int     :    指定包含几级下属

============================================================

*/
AS
BEGIN
SET NOCOUNT ON;

DECLARE @TabStaff TABLE (staff_id int NOT NULL);

IF ( @IncludePeers = 1 )
BEGIN
    -- 加入同级成员
    INSERT INTO @TabStaff (staff_id)
        SELECT staff_id 
            FROM dbo.uds_staff_in_position
            WHERE Position_id = @PositionID
END

IF ( @NumLowerLevels > 0 )
BEGIN
    IF ( @NumLowerLevels = 1 )
    BEGIN
        -- 只加入直属下级成员
        INSERT INTO @TabStaff (staff_id)
            SELECT staff_id
            FROM dbo.uds_staff_in_position
            WHERE Position_id in (
                    SELECT Position_id 
                        FROM dbo.uds_Position 
                        WHERE super_Position_id = @PositionID and super_Position_id <>Position_id
            )
    END
    ELSE
    BEGIN
        -- 加入递归多层下级成员
        WITH POS_SubTree AS
        (
            SELECT 0 AS SubLevel, @PositionID AS Position_ID          
            UNION ALL
            SELECT (ST.SubLevel + 1) AS SubLevel, P.Position_ID
                FROM dbo.UDS_Position P, POS_SubTree ST
                WHERE p.super_Position_id = ST.Position_ID and p.super_Position_id <> p.Position_id
        )
        INSERT INTO @TabStaff (staff_id)
			SELECT staff_id
            FROM dbo.uds_staff_in_position
            WHERE Position_id in (
                    SELECT Position_id 
                        FROM POS_SubTree
                        WHERE SubLevel <= @NumLowerLevels
            )
    END
END

--得到结果
SELECT S.*
    FROM dbo.UDS_Staff S INNER JOIN @TabStaff T ON S.Staff_ID = T.Staff_ID
    WHERE S.dimission = 0;

END
GO